package com.google.code.flexmetavalidator.reflection
{
    import flash.utils.describeType;
    import flash.utils.getDefinitionByName;
    import flash.utils.getQualifiedClassName;
    
    import mx.controls.Alert;
    

    public class MetaUtils
    {
		/**
		 * Method returns array of VariableInfo objects which match the given metadata name, type and value
		 */ 
        public static function getElementsByMeta(type : Class, metaName : String, metaParameterName : String, metaParameterValue : String) : Array
        {
            var xmlDescriptor : XML = describeType(type);
			var accessors : XMLList = getMetaTagged(xmlDescriptor.factory.accessor);
			var variables : XMLList = getMetaTagged(xmlDescriptor.factory.variable);
			
			var accessorsHavingMeta : XMLList = accessors.(metadata.(@name == metaName).length() > 0);
			var varsHavingMeta : XMLList = variables.(metadata.(@name == metaName).length() > 0);
			
			var elementsHavingMeta : XMLList = new XMLList();
			elementsHavingMeta += accessorsHavingMeta;
			elementsHavingMeta += varsHavingMeta;

            var retArray : Array = new Array();
            for each (var item : XML in elementsHavingMeta)
            {
				var matchingMetaName : XMLList = item..metadata.(@name=metaName);
				var matchingMetaType : XMLList = matchingMetaName.arg.(@key=="type");
				if (matchingMetaType.length() == 0) continue;
				var matchingMetaTypeValue : XMLList = matchingMetaType.(@value==metaParameterValue);
				if (matchingMetaTypeValue.length() == 0) continue;
				
                retArray.push(VariableInfo.fromXmlDescriptor(item));
            }

            return retArray;
        }
		
		private static function getMetaTagged(elements : XMLList) : XMLList
		{
			var returnList : XMLList = new XMLList();
			for each (var element : XML in elements)
			{
				if (element.metadata.length() > 0) returnList += element;
			}
			
			return returnList;
		}
		
		
    }
}